package com.zz.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zz.common.R;
import com.zz.entity.Club;
import com.zz.entity.Role;
import com.zz.entity.User;
import com.zz.entity.UserRole;
import com.zz.mapper.ClubMapper;
import com.zz.mapper.RoleMapper;
import com.zz.mapper.UserMapper;
import com.zz.mapper.UserRoleMapper;
import com.zz.service.UserService;
import com.zz.utils.AesEncryptUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.util.*;

/**
 * @author
 */
@Service
@Slf4j
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private UserRoleMapper userRoleMapper;

    @Autowired
    private ClubMapper clubMapper;

    @Autowired
    private RoleMapper roleMapper;

    /**
     * 根据用户名得到用户信息
     * @param name 名字
     * @return {@link User}
     */
    @Override
    public User getUserInfoByName(String name) {
        LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(User::getName,name);
        return userMapper.selectOne(queryWrapper);
    }

    /**
     * 根据角色名称获取权限信息
     * @param roles
     * @return
     */
    @Override
    public List<String> getUserPermissionInfo(List<String> roles) {
       return userMapper.getUserPermissionInfo(roles);
    }

    @Override
    public R<String> register(User user) {
        //AES解密
        user.setPassword(AesEncryptUtils.decrypt(user.getPassword()));
        user.setPhone(AesEncryptUtils.decrypt(user.getPhone()));
        user.setName(AesEncryptUtils.decrypt(user.getName()));

        log.info("解密后的数据：{}",user);

        //条件构造器
        LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(User::getId,user.getId());
        User one = userMapper.selectOne(queryWrapper);

        //用户已经注册
        if(one!=null){
            return R.error("该用户已注册！");
        }

        //向数据库添加用户
        userMapper.insert(user);

        // 此用户默认为普通用户
        UserRole userRole = new UserRole();
        userRole.setUserId(user.getId());
        // 3L代表普通用户
        userRole.setRoleId(3);

        // 插入数据到数据库
        userRoleMapper.insert(userRole);

        return R.success("注册成功！");
    }

    /**
     * 重置密码
     * @param map
     * @return
     */
    @Override
    public R<String> resetPassword(Map<String, String> map) {
        //获取前端传递的参数
        String newPassword = map.get("newPassword");
        String rPassword = map.get("rPassword");
        String phone = map.get("phone");
        String code = map.get("code");

        //AES解密
        newPassword=AesEncryptUtils.decrypt(newPassword);
        rPassword=AesEncryptUtils.decrypt(rPassword);
        phone=AesEncryptUtils.decrypt(phone);
        code=AesEncryptUtils.decrypt(code);

        log.info("newPassword:{},rPassword:{}",newPassword,rPassword);

        LambdaQueryWrapper<User> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(User::getPhone,phone);

        User user = userMapper.selectOne(wrapper);
        if(user==null){
            return R.error("您输入的手机号不存在，重置密码失败!");
        }

        if(newPassword.equals(rPassword)){
            user.setPassword(newPassword);
            userMapper.updateById(user);
            return R.success("重置密码成功!");
        }

        return R.error("两次密码输入不一致，重置密码失败!");
    }

    @Override
    public R<String> update(User user, HttpServletRequest request) {
        //从session中获取当前用户的用户名
        String userName = (String) request.getSession().getAttribute("user");

        //从数据库中查询用户
        LambdaQueryWrapper<User> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(User::getName, userName);

        User one = userMapper.selectOne(wrapper);

        //修改用户信息
        one.setNickname(user.getNickname());
        one.setAvatar(user.getAvatar());
        one.setPhone(user.getPhone());
        one.setName(user.getName());
        one.setSex(user.getSex());
        one.setAcademy(user.getAcademy());

        //数据库更新用户信息
        userMapper.updateById(one);

        // 更新session信息
        request.getSession().setAttribute("user",user.getName());

        return R.success("个人信息修改成功！");
    }

    @Override
    public R<User> info(HttpServletRequest request) {
        //从session中获取当前用户的用户名
        String userName = (String) request.getSession().getAttribute("user");

        LambdaQueryWrapper<User> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(User::getName, userName);
        User user = userMapper.selectOne(wrapper);

        // 获取当前用户身份
        // 条件过滤器
        LambdaQueryWrapper<UserRole> userRoleWrapper = new LambdaQueryWrapper<>();
        userRoleWrapper.eq(UserRole::getUserId, user.getId());
        List<UserRole> userRoles = userRoleMapper.selectList(userRoleWrapper);

        // 所有角色id集合
        ArrayList<Integer> roleIds = new ArrayList<>();
        for (UserRole userRole : userRoles) {
            roleIds.add(userRole.getRoleId());
        }
        LambdaQueryWrapper<Role> roleWrapper = new LambdaQueryWrapper<>();
        roleWrapper.in(Role::getId, roleIds);
        List<Role> roles = roleMapper.selectList(roleWrapper);

        // 设置身份集合（admin、leader、user）
        Set<String> set = new HashSet<>();

        // 获取所有角色id
        for (Role role : roles) {
            set.add(role.getRealname());
        }
        user.setIdentity(set);

        return R.success(user);
    }


    @Override
    public R<List<Club>> club(HttpServletRequest request)  {
        //从session中获取当前用户的用户名
        String userName = (String) request.getSession().getAttribute("user");

        //根据学号查询用户
        LambdaQueryWrapper<User> wrapper1 = new LambdaQueryWrapper<>();
        wrapper1.eq(User::getName,userName);
        User user = userMapper.selectOne(wrapper1);

        //根据社团id查询社团
        LambdaQueryWrapper<Club> wrapper2 = new LambdaQueryWrapper<>();
        wrapper2.eq(Club::getId, user.getClubId1());
        Club club1 = clubMapper.selectOne(wrapper2);
        LambdaQueryWrapper<Club> wrapper3 = new LambdaQueryWrapper<>();
        wrapper3.eq(Club::getId, user.getClubId2());
        Club club2= clubMapper.selectOne(wrapper3);
        LambdaQueryWrapper<Club> wrapper4 = new LambdaQueryWrapper<>();
        wrapper4.eq(Club::getId, user.getClubId3());
        Club club3 = clubMapper.selectOne(wrapper4);

        //将查询出来的所有社团加入列表
        ArrayList<Club> clubs = new ArrayList<>();
        clubs.add(club1);
        clubs.add(club2);
        clubs.add(club3);

        return R.success(clubs);
    }


    @Override
    public R<String> changePassword(Map<String, String> map, HttpServletRequest request) {
        // 获取前端参数
        int userId = Integer.parseInt(map.get("userId"));
        String oldPassword =  map.get("oldPassword");
        String  newPassword =  map.get("newPassword");
        String rPassword =  map.get("rPassword");
        // 参数解密
        oldPassword = AesEncryptUtils.decrypt(oldPassword);
        newPassword = AesEncryptUtils.decrypt(newPassword);
        rPassword = AesEncryptUtils.decrypt(rPassword);

        // 从session中获取当前用户的学号
        String userName = (String) request.getSession().getAttribute("user");

        // 从数据库中查询用户
        LambdaQueryWrapper<User> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(User::getName, userName);
        User user = userMapper.selectOne(wrapper);

        // 前端传来的学号与当前登录用户不一致
        if (!user.getId().equals(userId)){
            return R.error("学号输入错误！");
        }

        // 旧密码输入错误
        if (!oldPassword.equals(user.getPassword())){
            return R.error("旧密码输入错误！修改失败！");
        }

        // 新旧密码一致
        if (oldPassword.equals(newPassword)){
            return R.error("新旧密码一致！修改失败！");
        }

        // 新密码重复密码不一致
        if (!newPassword.equals(rPassword)){
            return R.error("两次密码输入不一致！修改失败！");
        }

        // 修改密码
        user.setPassword(newPassword);

        // 修改数据库
        userMapper.updateById(user);

        return R.success("修改密码成功！");
    }


    @Override
    public List<String> getUserRoleInfo(String principal) {
        return userMapper.getUserRoleInfoMapper(principal);
    }



}
